package com.siboxuetang.need.web.interceptor;

import com.siboxuetang.need.service.WechatService;
import com.siboxuetang.need.util.WebUtils;
import com.siboxuetang.need.vo.NeedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * Create Time: 2018年04月26日 14:42
 *
 * @author fin
 */
public class WechatInterceptor extends AuthInterceptor {

    private static final String WECHAT_REDIRECT_URL =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
    private static final String APPID = "APPID";
    private static final String SCOPE = "SCOPE";
    private static final String STATE = "STATE";
        public static final String SNSAPI_LOGIN = "snsapi_base";
//    private static final String SNSAPI_LOGIN = "snsapi_userinfo";
    private static final String REDIRECT_URI = "REDIRECT_URI";

    private static String serviceUrl = "http://test.dxtwangxiao.com";


    @Autowired
    private WechatService wechatService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        try {
            boolean pre = super.preHandle(httpServletRequest, httpServletResponse, o);
        } catch (NeedException e) {

            // 非ajax请求，重定向至用户登录
            if(!WebUtils.isAjaxRequest(httpServletRequest)) {
                // TODO: 加上微信公众号权限认证
                String appId = wechatService.getAppId();
                String url = WECHAT_REDIRECT_URL;
                url = url.replace(APPID, appId).replace(STATE, "none")
                        .replace(SCOPE, SNSAPI_LOGIN)
                        .replace(REDIRECT_URI, URLEncoder.encode(serviceUrl + "/wechat/validate/openid", "utf-8"));
                System.out.println(serviceUrl + "/wechat/validate/openid");

                httpServletResponse.sendRedirect(url);
                return false;
            }else{

            }
        }

        return true;

    }

}
